const allServices = require('../../controller/mysql')
const address = {
    // 地址列表查询
    addressList: (req, res) => {
        const user_id = req.user.user_id
        const sql = 'select * from address where user_id=?'
        allServices.query(sql, [user_id]).then(result => {
            res.send({
                code: 200,
                msg: '请求成功',
                res: result
            })
        })
    },
    // 地址信息
    addressInfo: (req, res) => {
        const address_id = req.query.address_id
        const user_id = req.user.user_id
        const sql = 'select * from address where address_id=? and user_id=?'
        allServices.query(sql, [address_id, user_id]).then(result => {
            res.send({
                code: 200,
                msg: '请求成功',
                res: result
            })
        })
    },
    // 地址编辑
    addressEdit: (req, res) => {
        const data = req.body;
        const sql = `UPDATE address SET phone_number=?, username=?, province=?, city=?, county=?, addressDetail=?, areaCode=?, isDefault=? WHERE address_id=?`;
        const params = [data.tel, data.name, data.province, data.city, data.county, data.addressDetail, data.areaCode, data.isDefault, data.id];
        allServices.query(sql, params).then(result => {
            if (result.affectedRows) {
                res.send({
                    code: 200,
                    msg: '成功'
                });
            }
        })
    },
    // 新增地址
    addressAdd: (req, res) => {
        try {
            const sql = `insert into address (user_id, username, phone_number, province, city, 
                county, addressDetail, areaCode, isDefault) values (?, ?, ?, ?, ?, ?, ?, ?, ?)`;
            const values = [
                req.user.user_id,
                req.body.name,
                req.body.tel,
                req.body.province,
                req.body.city,
                req.body.county,
                req.body.addressDetail,
                req.body.areaCode,
                req.body.isDefault
            ];
            allServices.query(sql, values).then(result => {
                if (result.affectedRows) {
                    res.send({
                        code: 200,
                        msg: '成功'
                    })
                }
            })
        } catch (error) {
            console.error(error);
            res.send({
                code: 500,
                msg: '服务器错误'
            })
        }
    }
}    
module.exports = address